<template>
  <div class="main">
    <!-- 搜索区域 -->
    <div class="top">
      <input
        type="text"
        placeholder="请输入城市名称"
        v-model="cityName"
        @keyup.enter="handleSearch"
        @input="handleInput"
      />
    </div>
    <div class="tip" v-if="cityName" @click="handleSearch">
      <p>{{ currentCity }}</p>
    </div>

    <!-- 近期天气区域 -->
    <div class="weather">
      <div class="weather-top">
        <div
          class="weather-item"
          v-for="(item, index) in forecastList1"
          :key="index"
        >
          <p class="date">{{ weekdays[index] }}</p>
          <p class="day">{{ formatDate(item.date) }}</p>
          <p class="item">{{ item.dayweather }}</p>
          <p class="wind">风力 {{ item.daypower }} 级</p>
        </div>
      </div>
      <div class="weather-bottom">
        <v-chart :option="chartOption"></v-chart>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useCodeStore } from '@/stores/code.js';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';

const router = useRouter();
const store = useCodeStore();
const { fetchWeatherByCity } = store;
const { nowWeather, nowWeatherall, cityName, weatherall } = storeToRefs(store);

// 计算属性：处理天气数据

const currentWeather = computed(() => {
  return nowWeather.value.lives?.[0] || {};
});

const forecastList1 = computed(() => {
  return weatherall.value.forecasts?.[0]?.casts || [];
});

const weekdays = computed(() => {
  if (!forecastList1.value || forecastList1.value.length < 4) {
    return ['今天', '明天', '', ''];
  }

  const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const today = new Date();
  const tomorrow = new Date(today);
  tomorrow.setDate(today.getDate() + 1);

  const day3 = new Date(forecastList1.value[2].date);
  const day4 = new Date(forecastList1.value[3].date);

  return ['今天', '明天', dayNames[day3.getDay()], dayNames[day4.getDay()]];
});

const currentCity = computed(() => {
  return currentWeather.value.city || '';
});

// 图表配置
const chartOption = computed(() => {
  const { xAxis, dayTemps, nightTemps } = getChartData();

  return {
    xAxis: {
      type: 'category',
      data: xAxis,
      show: false,
    },
    yAxis: {
      type: 'value',
      name: '温度(℃)',
      show: false,
    },
    grid: {
      left: 0,
      right: 0,
      top: 15,
      bottom: 10,
      containLabel: true,
    },
    series: [
      {
        name: '白天温度',
        type: 'line',
        data: dayTemps,
        smooth: true,
        lineStyle: { color: 'rgb(62, 97, 187)' },
        label: {
          show: true,
          position: 'top',
          formatter: (params) => `白${params.value}℃`,
          textStyle: { color: 'white' },
        },
      },
      {
        name: '夜晚温度',
        type: 'line',
        data: nightTemps,
        smooth: true,
        lineStyle: { color: '#98FB98' },
        label: {
          show: true,
          position: 'bottom',
          formatter: (params) => `晚${params.value}℃`,
          textStyle: { color: 'white' },
        },
      },
    ],
  };
});

// 方法封装
const handleSearch = async () => {
  if (!cityName.value.trim()) {
    console.warn('请输入城市名称');
    return;
  }

  const result = await fetchWeatherByCity(cityName.value.trim());
  if (result.success) {
    console.log('天气数据获取成功');
  } else {
    console.error('天气数据获取失败:', result.message);
  }
  router.push('/weather');
};

// 格式化日期
const formatDate = (dateStr) => {
  return dateStr.split('-').slice(1).join('-');
};
const handleInput = async () => {
  if (!cityName.value.trim()) {
    console.warn('请输入城市名称');
    return;
  }

  const result = await fetchWeatherByCity(cityName.value.trim());
  if (result.success) {
    console.log('天气数据获取成功');
  } else {
    console.error('天气数据获取失败:', result.message);
  }
  router.push('/add');
};

// 处理图表数据
const getChartData = () => {
  const casts = weatherall.value.forecasts?.[0]?.casts || [];
  return casts.reduce(
    (acc, item) => {
      acc.xAxis.push(formatDate(item.date));
      acc.dayTemps.push(item.daytemp);
      acc.nightTemps.push(item.nighttemp);
      return acc;
    },
    { xAxis: [], dayTemps: [], nightTemps: [] }
  );
};
</script>

<style scoped>
.main {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0 280px;
}
.top {
  margin-top: 25px;
  width: 100%;
}
.top input {
  width: 100%;
  height: 40px;
  padding: 0 10px;
  border: none;
  font-size: 16px;
  background-color: rgb(0 102 138);
  border-bottom: 1px solid rgb(255, 255, 255);
  color: rgb(255, 255, 255);
  transition: all 0.3s ease;
  outline: none;
}
.top input:focus {
  border: none;
  box-shadow: 0px 0px 10px 0px rgb(47, 69, 77);
}
::placeholder {
  color: rgb(168, 167, 167);
}
.text-center {
  margin-top: 30px;
  font-size: 16px;
  color: rgb(255, 255, 255);
  font-weight: 400;
}
.text-bottom {
  margin-top: 30px;
  font-size: 16px;
  color: rgb(255, 255, 255);
  font-weight: 400;
  text-align: left;
  width: 100%;
}
.weather {
  width: 100%;
  background-color: rgb(0, 78, 113);
  margin-top: 10px;
  border-radius: 5px;
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 40px;
  color: rgb(255, 255, 255);
}
.weather-top {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 20px;
  margin: 0 auto;
}
.weather-item {
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.weather-bottom {
  margin-top: 50px;
  width: 100%;
  height: 200px;
}
.weathernow {
  color: white;
  display: flex;
  flex-direction: column;
  gap: 25px;
  width: 100%;
  border-bottom: 1px solid rgb(255, 255, 255, 0.2);
}
.weather-top {
  background-color: rgb(0, 78, 113);
  width: 100%;
  padding: 10px;
  text-align: center;
}
.weather-main {
  display: flex;
  flex-direction: column;
  gap: 20px;
  text-align: center;
  margin-bottom: 25px;
}
.tip {
  background-color: rgb(0, 78, 113);
  color: white;
  width: 100%;
  height: 50px;
  padding: 12px;
  margin-top: 10px;
}
</style>
